$(function () {
    obj.init();

});

var obj = new function () {
    'use strict';
    return {
        dataGrid:null,
        dgState:'close',
        iBPPId:null,
        init:function () {
            this.iBPPId = xhTool.getQuery('iBPPId');
            this.dataGrid = new xhDataGrid($('#list'), 'device/getPlanReceive',{iBPPId:this.iBPPId});
            this.dataGrid.parseToolbar().init().activeButton(['bt_list_chargeMode'], ['bt_list_del','bt_list_get','bt_list_sign','bt_list_planContact','bt_list_print']);
            this.funObj().bindDataGridEvent();
            this.listener();
        },
        listener:function () {
            var $this = this;
            var $length = 0;
            //获取区域数据
            $('#school_area').combotree({
                url: 'getDepData',
                animate:true,
                onLoadSuccess:function(node,data){
                    $length = data.length;
                    $.each(data,function (id,value) {
                        if (value.children !== undefined) {
                            $length = $length + value.children.length;
                        }
                    })
                },
                onShowPanel:function(){
                    if ($length <= 8){
                        $(this).combobox('panel').height("auto");//高度自适应
                    }else{
                        $(this).combobox('panel').height("200");//高度自定义
                    }
                },
                onBeforeSelect: function (node) {
                    var t = $(this).tree;
                    var isLeaf = t('isLeaf', node.target);
                    if (!isLeaf) {//选择的不是叶子节点
                        return false;
                    }
                }
            });

            //新增事件按钮
            $('#bt_list_get').on('click',function () {
                if (xhExtra.buttonDisabled($(this))) {
                    return false;
                }
                $this.funObj().openQR();
            });
            //删除
            $('#bt_list_del').on('click',function () {
                if (xhExtra.buttonDisabled($(this))) {
                    return false;
                }
                $this.funObj().askDelQuestion();
            });

            //搜索
            $('#bt_list_search').on('click',function () {
                $this.funObj().search();
            });

            //新增
            $('#bt_list_add').on('click',function () {
                $this.funObj().openAddForm();
            });
            //其他申领
            $('#bt_list_addOther').on('click',function () {
                $this.funObj().openOtherForm();
            });

            //打印
            $('#bt_list_print').on('click',function () {
                if (xhExtra.buttonDisabled($(this))) {
                    return false;
                }
                $this.funObj().print();
            });
            //收起
            $('#bt_list_pack').click(function () {
                $this.funObj().pack();
            });
            //展开
            $('#bt_list_expand').click(function () {
                $this.funObj().expand();
            });

            $('#bt_list_sign').click(function () {
                if (xhExtra.buttonDisabled($(this))) {
                    return false;
                }
                $this.funObj().signTablet();
            });
            
            $('#bt_list_chargeMode').click(function () {
                if (xhExtra.buttonDisabled($(this))) {
                    return false;
                }
                $this.funObj().chargeModeAction();
            });
            //编辑流程计划关联
            $('#bt_list_planContact').click(function () {
                if (xhExtra.buttonDisabled($(this))) {
                    return false;
                }
                $this.funObj().editPlanContact();
            });
        },
        funObj:function () {
            var $this = this;
            return {
                openAddForm:function () {
                    window.top.xhTop.showModal({
                        title: '学生机申领',
                        content: xhTool.getFrameString('device/studentApply', {}, 340),
                        button: '确认',
                        backClose:false
                    })
                },
                openOtherForm:function(){
                    window.top.xhTop.showModal({
                        title: '其他申领',
                        content: xhTool.getFrameString('device/otherApply', {}, 340),
                        button: '确认',
                        backClose:false
                    })
                },
                bindDataGridEvent:function () {
                    if (!$this.iBPPId){
                        $this.dataGrid.onDblClickRow = function (rowIndex, rowData) {
                            if ($(rowData['iState']).text() == '待领用') {
                                window.top.xhTop.showModal({
                                    title: '修改类型',
                                    content: xhTool.getFrameString('device/modifyApTablet', {id:rowData['iRTId']}, 340),
                                    button: '确认',
                                    backClose:false
                                });
                            } else if ($(rowData['iState']).text() == '已领用') {
                                window.top.xhTop.showModal({
                                    title: '申领出库明细',
                                    content: xhTool.getFrameString('ims/detail/outList', {typeId:rowData['iRTId'],type:2}, 500),
                                    backClose:false
                                });
                                // window.top.xhTop.showModal({
                                //     title: '修改收费模式',
                                //     content: xhTool.getFrameString('device/modifyChargeMode', {id:rowData['iRTId']}, 340),
                                //     button: '确认',
                                //     backClose:false
                                // });
                            }
                        };
                    }
                    //加载完毕
                    $this.dataGrid.onLoadSuccess=function (data) {
                        $this.dataGrid.clear();
                        if($this.dgState == 'open'){
                            $this.funObj().expand();
                        }else if ($this.dgState == 'close'){
                            $this.funObj().pack();
                        }
                    };
                    $this.dataGrid.command({
                        view:detailview,
                        detailFormatter:function(index,row){
                            var str='<div class="ddv" style="padding:5px 0;overflow: auto;"  >' ;
                                if (row['prodDetail']) {
                                    str +='  <div style="margin-bottom: 5px;">商品明细:</div>' +
                                        '         <table style="margin-bottom: 5px;">' +
                                        '                <tr><th style="width: 120px;text-align: center">商品名称</th><th style="width: 75px;text-align: center">商品数量</th><th style="width: 75px;text-align: center">类型</th></tr>' +
                                        '               ' + row['prodDetail'] +
                                        '         </table>';
                                }

                                if (row['tchDetail']) {
                                    str += '<div style="margin-bottom: 5px;">领用详情:</div>' +
                                        '        <table style="margin-bottom: 5px;">' +
                                        '               <tr><th style="width: 75px;text-align: center">姓名</th><th style="width: 120px;text-align: center">机型</th><th style="width: 180px;text-align: center">设备号</th></tr>' +
                                        '                '+ row['tchDetail'] +
                                        '        </table>';
                                }
                                if (row['mDesc']) {
                                    str += '<div style="margin-bottom: 5px;">备注:</div>' +
                                        '   <div >'+row['mDesc']+'</div>';
                                }
                            str+='</div>';
                            return str;

                        },
                        onExpandRow: function(index,row){
                            var ddv = $(this).datagrid('getRowDetail',index).find('div.ddv');
                            ddv.panel({
                                // height:200,
                                width:780,
                                border:false,
                                cache:false,
                                onLoad:function(){
                                    $this.dataGrid.command('fixDetailRowHeight',index);
                                    $this.dataGrid.command('fixDetailRowWidth',index);
                                }
                            });
                            $this.dataGrid.command('fixDetailRowHeight',index);
                        }
                    });
                },
                openQR:function () {
                    xhExtra.ajaxRequest('device/planQR', {iRTId: $this.dataGrid.getSelectValue('iRTId')}, {check: true}, function(result) {
                        window.top.swal({
                            title: '领用清单-' + $this.dataGrid.getSelectValue('iCreateUserId'),
                            html: '<img src="' + result.msg + '" width="80%">',
                            showConfirmButton: true,
                            confirmButtonText: '确认'
                        }).then(function () {}, function (dismiss) {});
                    });
                },
                askDelQuestion:function () {
                    var id = $this.dataGrid.getSelectValue('iRTId');
                    xhExtra.askChangeStatus('device/delApply',{id:id},null,null,function (res) {
                        window.top.xhTop.showSuccess(res.msg);
                        $this.dataGrid.reload();
                    });
                },
                search:function () {
                    var key   = xhExtra.getValue($('#list_search'));
                    var state = xhExtra.getValue($('#select_state'));
                    var type  = xhExtra.getValue($('#select_type'));
                    var school_area = $('#school_area').combotree('getValue');

                    $this.dataGrid.reload({key:key, state:state, type:type,iBPPId:$this.iBPPId, school_area:school_area});
                },
                print:function () {
                    var id = $this.dataGrid.getSelectValue('iRTId');
                    window.top.xhTop.showModal({
                        title: '销售单打印预览',
                        content: xhTool.getFrameString('device/printReceiveData', {id: id}, 400),
                        // width: 800,
                        size:'lg',
                        button: '打印'
                    })
                },
                pack:function () {
                    $this.dgState = 'close';
                    var row = $this.dataGrid.command("getRows");
                    for (var r = 0; r < row.length; r++)
                    {
                        $this.dataGrid.command("collapseRow",r);
                    }
                },
                expand:function () {
                    $this.dgState = 'open';
                    var row = $this.dataGrid.command("getRows");
                    for (var r = 0; r < row.length; r++)
                    {
                        $this.dataGrid.command("expandRow",r);
                    }
                },
                signTablet:function () {
                    var id = $this.dataGrid.getSelectValue('iRTId');
                    xhExtra.askChangeStatus('device/signTablet',{iRTId:id},null,'请仔细核对清单,确认签收?',function (res) {
                        window.top.xhTop.showSuccess(res.msg);
                        $this.dataGrid.reload();
                    })
                },
                chargeModeAction:function () {
                    var ids = $this.dataGrid.getSelectValues('iRTId');
                    window.top.swal({
                        showCancelButton: true,
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        showLoaderOnConfirm: true,
                        allowOutsideClick: false,
                        title: '修改收费模式',
                        html: '<select id="iChargeMode" class="form-control">\n' +
                        '                            <option value="">请选择</option>\n' +
                        '                            <option value="1">购买</option>\n' +
                        '                            <option value="2">租用</option>\n' +
                        '                            <option value="3">借用</option>\n' +
                        '      </select>',
                        preConfirm: function() {
                            var $chargeMode = $('#iChargeMode',window.top.document).val();
                            return new Promise(function (resolve, reject) {
                                if(!$chargeMode){
                                    reject('收费模式不能为空！');
                                }
                                else {
                                    resolve($chargeMode);
                                }
                            })
                        }
                    }).then(function ($chargeMode) {
                        xhExtra.ajaxRequest('device/modifyChargeMode',{ids:ids,chargeMode:$chargeMode},{},function (res) {
                            window.top.xhTop.showSuccess(res.msg);
                            $this.dataGrid.reload();
                        })
                    },function (dismiss) {
                        return false;
                    });
                },
                editPlanContact:function () {
                    var schoolId = $this.dataGrid.getSelectValue('iSchoolId');
                    var id = $this.dataGrid.getSelectValue('iRTId');
                    var iType = $this.dataGrid.getSelectValue('iType');
                    var iBPPId = $this.dataGrid.getSelectValue('iBPPId');
                    var cuId = $this.dataGrid.getSelectValue('cuId');
                    if (!schoolId && !cuId) {
                        window.top.xhTop.showError('错误', '未获取到必要参数，客户id或学校id');
                        return false;
                    }
                    // if (iType == '自用机') {
                    //     window.top.xhTop.showError('错误', '自用机无法关联流程计划');
                    //     return false;
                    // }
                    xhExtra.ajaxRequest('device/ajaxGetPlanName',{schoolId:schoolId,cuId:cuId},{},function (res) {
                        var html = '';
                        html = '<select id="iBPPId" class="form-control">\n' +
                            '                  <option value=""   style="display: none;">请选择一个流程计划</option>\n';
                        if (res.length > 0) {
                            $.each(res, function (index,item) {
                                html += '      <option value="'+item['id']+'" ';
                                if (iBPPId && iBPPId == item['id']) {
                                    html += ' selected ';
                                }
                                html +='>'+item['name']+'</option>\n' ;
                            });
                        }
                        html +='      </select>';
                        window.top.swal({
                            width:700,
                            showCancelButton: true,
                            confirmButtonText: '确认',
                            cancelButtonText: '取消',
                            showLoaderOnConfirm: true,
                            allowOutsideClick: false,
                            title: '修改关联的流程计划',
                            html: html,
                            preConfirm: function() {
                                var iBPPId = $('#iBPPId',window.top.document).val();
                                return new Promise(function (resolve, reject) {
                                    if(!iBPPId){
                                        reject('计划id不能为空！');
                                    }
                                    else {
                                        resolve(iBPPId);
                                    }
                                })
                            }
                        }).then(function (iBPPId) {
                            xhExtra.ajaxRequest('device/modifyGetBpmId',{id:id,iBPPId:iBPPId},{},function (res) {
                                window.top.xhTop.showSuccess(res.msg);
                                $this.dataGrid.reload();
                            })
                        },function (dismiss) {
                            return false;
                        });
                    });

                }
            }
        }
    }
};